import express from "express";
import createHttpError from "http-errors";
import path from "node:path";
import url from "node:url";
import fs from "node:fs";
import markdown from "./lib/markdown.mjs";
import cors from "cors";
import https from "node:https";

const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const port = process.env.port ?? 80;
const porthttps = process.env.porthttps ?? 443;
const app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(cors());

// app.use(markdown(path.join(__dirname, "markdown")));
app.use(express.static(path.join(__dirname, "public")));

app.use(markdown(path.join(__dirname, "docs")));

app.use(function (req, res, next) {
  //   next(createError(404));
  next(createHttpError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

app.listen(port, () => {
  console.log(`http listening on port ${port}`);
});

const options = {
  key: fs.readFileSync("./dev.thinjs.com.key"),
  cert: fs.readFileSync("./dev.thinjs.com.pem"),
};

https.createServer(options, app).listen(porthttps, () => {
  console.log(`https listening on port ${porthttps}`);
});

export default app;
